﻿/******************************************************
* author :  cwj
* email  :  chenwenji_360@live.com 
* history:  created by cwj 2015/8/15 9:14:52 
* clrversion :4.0.30319.42000
******************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Data;

namespace Machine.DataAccess.Transaction
{
    class DataAccessExecutionContext:IDisposable
    {
        [ThreadStatic]
        private static DataAccessExecutionContext _current;
        public static DataAccessExecutionContext Current { get { return _current; } set { _current = value; } }

        public DataAccessExecutionContext(ProviderElement providerElement)
        {
            this.ProviderElement = providerElement;
            this.Factory = DbProviderFactories.GetFactory(this.ProviderElement.Provider);
            this.DbConnection = this.Factory.CreateConnection();
            this.DbConnection.ConnectionString = this.ProviderElement.ConnectionString;
            if (this.DbConnection.State == ConnectionState.Closed) this.DbConnection.Open();
            this.Transaction = this.DbConnection.BeginTransaction();
            //this.DbCommand = DbConnection.CreateCommand();
            //this.DbCommand.Transaction = this.Transaction;
        }

        public ProviderElement ProviderElement { get; private set; }
        public DbConnection DbConnection { get; private set; }
        public DbProviderFactory Factory { get; private set; }
        public DbTransaction Transaction { get; private set; }
        //public DbCommand DbCommand { get; private set; }

        public void ResetTransaction()
        {
            this.Transaction = this.DbConnection.BeginTransaction();
        }

        public void Dispose()
        {
            //this.DbCommand.Dispose();
            this.Transaction.Dispose();
            this.DbConnection.Dispose();
        }
    }
}
